//* detect touch devices 
function is_touch_device() {
	return !!('ontouchstart' in window);
}

// 增加class名loader
document.documentElement.className += 'loader';

// JavaScript in Bootstrap
// http://twitter.github.com/bootstrap/javascript.html
$(document).ready(function() {

	$(document).ajaxStart(function(e) {
		
		//document.documentElement.className += 'loader-part';
	}).ajaxStop(function(e) {
		// 清除loader图标
		
		//setTimeout('$("html").removeClass("loader-part")',500);
	});
	
	// @example <p id="one" class="some_class" data="{item_id: 1, item_label: 'Label'}">This is a p</p>
	// 初始化metadata(默认以class为查找点)
	$.metadata.setType("attr", "rel");
	
	if (jQuery.datepicker) {
		//datepicker 默认使用中文
		jQuery.datepicker.setDefaults( jQuery.datepicker.regional[ "zh-CN" ] );
	}

	/*var loader = jQuery('<div id="loader"><img src="../images/loaders/loader11.gif" alt="loading..." /></div>')
	.css({position: "relative", top: "1em", left: "25em", display: "inline"})
	.appendTo("body")
	.hide();
	jQuery().ajaxStart(function() {
		loader.show();
	}).ajaxStop(function() {
		loader.hide();
	}).ajaxError(function(a, b, e) {
		throw e;
	});*/
	
	// 提示信息5秒后消失
	if ($('.notification').length) {
		if (!$('.notification').hasClass('show')) {
			setTimeout("$('.notification').fadeOut(800)", 5000);		
		}
	}
	
	// 一些内容的渲染
	common_render = {
		config : {
			
		},
		init : function() {
			var blocking = true;
			jQuery('.widgetlist a').hover(function(){
				jQuery(this).switchClass('default', 'hover', '200', 'swing', function(){
					blocking = false;
				});
			},function(){
				jQuery(this).switchClass('hover', 'default', '100', 'swing', function(){
					
				});
			});
		},
		callback : function() {
			this.init();
		}
	};
	
	/*
	 * js验证对象
	 * 
	 */
	//jquery-validation @see:http://bassistance.de/jquery-plugins/jquery-plugin-validation/
	common_validation = {
		config : {
			//onfocusout: false,
			debug: false,
			//onclick: false,
			onkeyup: false,
			meta: "validate",
			errorElement: "em",
			//errorContainer: $(".warning"),
			errorPlacement: function(error, element) {
				var span = element.parents("span");
				if (span && span.length>0){
					// 存在span在其后显示提示
					error.appendTo(span);
				} else {
					// 不存在span,在下一行显示信息
					error.css({'padding-left':'120px'});
					element.after(error).after("<br />");
				}
				//resieze colorbox
				common_box.resize();
			},
			/*submitHandler: function(form) {
				//$(form).ajaxSubmit();
				//alert("Correct captcha!");
				//$(form).submit();
			},
			invalidHandler: function(form, validator) {
			},*/
			success: function(label) {
				label.text("ok!").addClass("success");
			}
		},
		init : function() {
			if (!is_touch_device() && $.validator) {
				// 加入一个自定义方法
				$.validator.addMethod("custom", function(value, element) {
					var url = $(element).attr('remote');
					if ($(element).has("em")) {
						$(element).parents("span").append("<span><img src='../images/loaders/loader1.gif'></span>");
					} else {
						$(element).val(111);
						$(element).parents("span").append("<span><img src='../images/loaders/loader1.gif'></span>");
					}
					return $.validator.methods.remote.call(this, value, element, {
						url : "/cms/manage/User/create", //"/cms/js/va.js",
					      data: {
					    	  // 自动对象加载
					      }
					});
				}, $.validator.messages.remote);
				
				// form.validate:not(.ajaxform)
				this.config.validator = $("form.validate:not(.ajaxform)").bind("invalid-form.validate", function() {
					//$(this).append("<p>Your form contains " + common_validation.config.validator.numberOfInvalids() 
					//		+ " errors, see details below.</p>");
				}).validate(this.config);
			}
		},
		reset: function() {
			if(this.config.validator) {
				this.config.validator.resetForm();
			}
		},
		destory : function(){
		}
	};
	
	/*
	 * tooltips 
	 * ttip_b:bottom;
	 * ttip_t:top;
	 * ttip_l:left;
	 * ttip_r:right;
	 */
	common_tips = {
		init : function() {
			if (!is_touch_device()) {
				var shared = {
					delay: { show: 500, hide: 100 },
					trigger:"hover"
				};
				if ($('.tooltip_b').length) {
					//$('.tooltip_b').tooltip();
				};
			}
		}
	};
	
	/*
	 * colorbox
	 * 
	 */
	//colorbox @see http://www.jacklmoore.com/colorbox
	common_box = {
		init: function() {
			if (!is_touch_device()) {
				if ($('a.ajax').length) {
					//$('.tooltip_b').tooltip();
					var el = $('a.ajax');
					el.colorbox({
						opacity:0.4,
						onComplete: function(){
							if (base) {
								base.config.blocking=false;
							}
							// 是否需要验证?
							var validator = $('form.validate', $('#cboxLoadedContent')).validate(common_validation.config);
							$('.cancel', $('#cboxLoadedContent')).click(function(){
								$.fn.colorbox.close();
								return false;	//we use return false because we use button and to prevent form submission 
							});
							$('.ajaxform', $('#cboxLoadedContent')).submit(function() {
								if (validator && validator.numberOfInvalids() > 0) {
									common_box.resize();
									return false;
								}
								var formdata = $(this).serialize();		//get all form data
								var url = $(this).attr('action');		//get the url to be submitted
								$('.loader').show();
								common_box.resize();
								$.post(url, formdata, function(data){
									//if success, then show message notification as success message
									//$('div[key="notify"]').addClass('notifySuccess').append(data);
									$('div[key="notify"]').empty().append(data);
									//$('.notifyMessage').append(data);
									//otherwise
									//$('.notifyMessage').addClass('notifyError');
									$('.loader').hide();
									//$.fn.colorbox.resize();
									common_box.resize();
								});
								return false;
							});
							//$.fn.colorbox.resize();
							common_box.resize();
							common_render.callback();
						},
						onCleanup: function() {
							// 关闭前做阻塞设置
							if (base) {
								base.config.blocking=true;
							}
							return true;
						}
					});
				};
			}
		},
		resize: function() {
			if ($.fn.colorbox) {
				$.fn.colorbox.resize();
			}
		}
	};
	
	/*
	 * chosen-master
	 * 
	 */
	//chosen-master @see http://harvesthq.github.com/chosen/
	common_choose = {
		config: {
				
		},
		init : function() {
			if (!is_touch_device()) {
				var option = {
					max_selected_options: 5,
					allow_single_deselect:false,
					no_results_text: "没有匹配的结果",
					trigger:"hover"
				};
				// 单选
				if ($('select[key="single"]').length) {
					$('select[key="single"]').chosen({allow_single_deselect:true, no_results_text:option.no_results_text}).change(function(e, t){
						//var value = $(this).val();
						//$(this).trigger("liszt:updated");
					});
				};
				// 多选
				if ($('select[key="multiple"]').length) {
					$('select[key="multiple"]').chosen(option);
				};
			}
		}
	};
	
	common_datepicker = {
			config : {
				
			},
			init : function() {
				if (!is_touch_device()) {
					if ($('.datepicker').length) {
						//$('#datepicker').datepicker({changeYear: true});
						$('.datepicker').datepicker({changeYear: true});
					}
				}
			}
	};
	
	common_checkbox = {
			config : {
				
			},
			init : function() {
				if (!is_touch_device()) {
					// 所有checkbox,排除class=yes_no|on_off|enabled_disabled部分
					$('input[type=checkbox]:not(.yes_no,.on_off,.enabled_disabled)').each(function(){
						var t = $(this);
						/*if (t.attr('checked') == 'checked') {
							t.wrap('<span class="checkbox checked"></span>');	
						} else {
							t.wrap('<span class="checkbox checked"></span>');
						}*/
						if (t.attr('checked')) {
							t.wrap('<span class="checkbox checked"></span>');
						} else {
							t.wrap('<span class="checkbox"></span>');
						}
						
						t.click(function(){
							if(jQuery(this).is(':checked')) {
								t.attr('checked',true);
								t.parent().addClass('checked');
							} else {
								t.attr('checked',false);
								t.parent().removeClass('checked');
							}
						});
					});	
				}
			}
	};
	
	// jQuery UI ：Tabs
	common_tabs = {
		config : {
			
		},
		init : function(){
			jQuery('#tabs').tabs({
				// nothins.
			});
		}
	};
	
	/*
	 * iButton
	 * 
	 */
	//chosen-master @see http://www.givainc.com/labs/ibutton_jquery_plugin.htm
	common_ibutton = {
		config: {
			
		},	
		init : function() {
			if (!is_touch_device()) {
				//$('input[type=checkbox].ibutton').iButton();
				//$('input[type=radio].ibutton').iButton();
				// 使用图标
				/*$('.on_off :checkbox, .on_off :radio').iButton({
					labelOn: "",
					labelOff: ""
					//enableDrag: false
				});
				// 不使用图标
				$('.yes_no :checkbox, .yes_no :radio').iButton({
					//labelOn: "On",
					//labelOff: "Off",
					//enableDrag: false
				});
				$('.enabled_disabled :checkbox, .enabled_disabled :radio').iButton({
					//labelOn: "Enabled",
					//labelOff: "Disabled",
					//enableDrag: false
				});*/
				if ($('input:checkbox.yes_no').length) {
					$('input:checkbox.yes_no').iButton({
						//labelOn: "Enabled",
						//labelOff: "Disabled",
						enableDrag: true
					});
				}
			}
		}
	};
	
	
	common_validation.init();
	common_box.init();
	common_tips.init();
	common_choose.init();
	common_datepicker.init();
	common_checkbox.init();
	common_tabs.init();
	
	common_ibutton.init();
	
	// 清除loader图标
	setTimeout('$("html").removeClass("loader")',500);
});